'''
工具模块
'''
import functools
import time
import os
import fcntl
from log import log
from settings import COSTTIME_DEBUGGING, DB_LOCK_FILE, UTIL_LOG_FILE, MIN_DEBUG_COSTTIME, STAT_LOCK_FILE

logging = log(filename=UTIL_LOG_FILE, level=log.INFO)

def valuleCheck(func):
    '''
    检查数值是否为非负数的装饰器
    '''
    @functools.wraps(func)
    def wrapper(*args, **kw):
        if args[0] < 0:
            raise ValueError('please input a number greater than 0 ')
        return func(*args, **kw)
    return wrapper



def dbfilelock(func):
    '''
    数据库文件锁装饰器
    '''
    @functools.wraps(func)
    def wrapper(*args, **kw):        
        if not os.path.exists(DB_LOCK_FILE):
            # create the counter file if it doesn't exist
            file = open(DB_LOCK_FILE, "w")
            file.write("0")
            file.close()
        logging.info('dbfilelock lock')
        f = open(DB_LOCK_FILE)
        fcntl.flock(f, fcntl.LOCK_EX)
        ret = func(*args, **kw)
        f.close()
        logging.info('dbfilelock unlock')
        return ret
    return wrapper

def statfilelock(func):
    '''
    统计文件锁装饰器
    '''
    @functools.wraps(func)
    def wrapper(*args, **kw):        
        if not os.path.exists(STAT_LOCK_FILE):
            # create the counter file if it doesn't exist
            file = open(STAT_LOCK_FILE, "w")
            file.write("0")
            file.close()
        logging.info('statfilelock lock')
        f = open(STAT_LOCK_FILE)
        fcntl.flock(f, fcntl.LOCK_EX)
        ret = func(*args, **kw)
        f.close()
        logging.info('statfilelock unlock')
        return ret
    return wrapper
def costCount(func):
    '''
    执行函数耗时的log装饰类
    '''
    @functools.wraps(func)
    def wrapper(*args, **kw):
        if COSTTIME_DEBUGGING:
            start = time.process_time()
        ret = func(*args, **kw)
        if COSTTIME_DEBUGGING:
            costTime = time.process_time() - start
            if costTime > MIN_DEBUG_COSTTIME:
                logging.info('{} cost {:.3f}'.format(func.__name__, costTime))
        return ret
    return wrapper